package com.itboye.lottery.retrofit;


import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by YJY on 2017/10/12.
 */

class RxMethod {

    // 统一正常返回处理
    public class HttpResultFunc<T> implements Func1<HttpResponse<T>, T> {
        @Override
        public T call(HttpResponse<T> resultFunc) {
            return resultFunc.getData();
        }
    }

//    // 统一正常返回处理
//    public class OtherResultFunc<T> implements Func1<T,T>
//    {
//        @Override
//        public T call(T t) {
//            return t;
//        }
//    }

    // 统一异常处理
    public class HttpResultErrorFunc<T> implements Func1<Throwable, Observable<T>> {
        @Override
        public Observable<T> call(Throwable t) {
            return Observable.error(ExceptionHandle.handleException(t));
        }
    }

    public <T> void onSubscribe(Observable<HttpResponse<T>> observable, Subscriber<HttpResponse<T>> subscriber) {
        observable
                .onErrorResumeNext(new HttpResultErrorFunc<>())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    // 统一添加线程切换
    public <T> void toSubscribe(Observable<HttpResponse<T>> observable, Subscriber<T> subscribe) {
        observable.map(new HttpResultFunc<T>())
                .onErrorResumeNext(new HttpResultErrorFunc<T>())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscribe);
    }

    //    public <T> void toOtherSubscribe(Observable<T> observable, Subscriber<T> subscribe){
//        observable.map(new OtherResultFunc<T>()).onErrorResumeNext(new HttpResultErrorFunc<T>())
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscribe);
//    }

}
